package com.sky.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.ReportMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;

@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
    private ReportMapper reportMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WorkspaceService workspaceService;

    @Override
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
        StringJoiner stringJoiner=new StringJoiner(",");
        stringJoiner.add(begin.toString());
        List<LocalDate> dateList=new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)){
            begin=begin.plusDays(1);
            dateList.add(begin);
            stringJoiner.add(begin.toString());
        }

        StringJoiner turnOver=new StringJoiner(",");
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map<String,Object> map=new HashMap<>();
            map.put("beginTime",beginTime);
            map.put("endTime",endTime);
            map.put("status", Orders.COMPLETED);
            BigDecimal dailyAmount= orderMapper.countByStatusAndBeginEndTime(map);
            turnOver.add(dailyAmount==null?"0.0":dailyAmount.toString());
        }

        return TurnoverReportVO.builder().dateList(stringJoiner.toString()).turnoverList(turnOver.toString()).build();
    }

    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        StringJoiner dateStringjoiner=new StringJoiner(",");
        dateStringjoiner.add(begin.toString());
        List<LocalDate> dateList=new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)){
            begin=begin.plusDays(1);
            dateList.add(begin);
            dateStringjoiner.add(begin.toString());
        }
        StringJoiner totalUserList=new StringJoiner(",");
        StringJoiner newUserList=new StringJoiner(",");
        for (LocalDate localDate : dateList) {
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);
            Integer userCount= userMapper.countByBeginEndTime(null,endTime);
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            Integer dailyUserCount = userMapper.countByBeginEndTime(beginTime, endTime);
            totalUserList.add(userCount.toString());
            newUserList.add(dailyUserCount.toString());
        }

        return UserReportVO.builder().dateList(dateStringjoiner.toString()).newUserList(newUserList.toString())
                .totalUserList(totalUserList.toString()).build();
    }

    @Override
    public OrderReportVO orderStatistics(LocalDate begin, LocalDate end) {
        StringJoiner dateStringjoiner=new StringJoiner(",");
        dateStringjoiner.add(begin.toString());
        List<LocalDate> dateList=new ArrayList<>();
        dateList.add(begin);
        LocalDate date=begin;
        while (!date.equals(end)){
            date=date.plusDays(1);
            dateList.add(date);
            dateStringjoiner.add(date.toString());
        }
        Map<String,Object> queryMap=new HashMap<>();
        queryMap.put("beginTime",LocalDateTime.of(begin,LocalTime.MIN));
        queryMap.put("endTime",LocalDateTime.of(end,LocalTime.MAX));
        Integer totalOrderCount = orderMapper.getNumberByStatusAndBeginEndTime(queryMap);
        queryMap.put("status",Orders.COMPLETED);
        Integer validOrderCount = orderMapper.getNumberByStatusAndBeginEndTime(queryMap);
        Double orderCompletionRate=1.0*validOrderCount/totalOrderCount;

        StringJoiner orderCountList=new StringJoiner(",");
        StringJoiner validOrderCountList=new StringJoiner(",");
        for (LocalDate localDate : dateList) {
            Map<String,Object> subQueryMap=new HashMap<>();
            subQueryMap.put("beginTime",LocalDateTime.of(localDate,LocalTime.MIN));
            subQueryMap.put("endTime",LocalDateTime.of(localDate,LocalTime.MAX));
            Integer dailyOrderNumber = orderMapper.getNumberByStatusAndBeginEndTime(subQueryMap);
            subQueryMap.put("status",Orders.COMPLETED);
            Integer dailyValidOrderNumber = orderMapper.getNumberByStatusAndBeginEndTime(subQueryMap);
            orderCountList.add(dailyOrderNumber+"");
            validOrderCountList.add(dailyValidOrderNumber+"");
        }
        return OrderReportVO.builder()
                .dateList(dateStringjoiner.toString())
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .orderCountList(orderCountList.toString())
                .validOrderCountList(validOrderCountList.toString())
                .build();
    }

    @Override
    public SalesTop10ReportVO top100(LocalDate begin, LocalDate end) {
        LocalDateTime beginDateTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endDateTime = LocalDateTime.of(end, LocalTime.MAX);
        List<GoodsSalesDTO> goodList=orderMapper.getTop10Goods(beginDateTime,endDateTime);
        StringJoiner nameList=new StringJoiner(",");
        StringJoiner numberList=new StringJoiner(",");
        for (GoodsSalesDTO salesDTO : goodList) {
            nameList.add(salesDTO.getName());
            numberList.add(salesDTO.getNumber()+"");
        }
        return SalesTop10ReportVO.builder().nameList(nameList.toString())
                .numberList(numberList.toString()).build();
    }

    @Override
    public void exportBusinessData(HttpServletResponse response) {
        LocalDate begin = LocalDate.now().minusDays(30);
        LocalDate end = LocalDate.now().minusDays(1);
        BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(begin, LocalTime.MIN), LocalDateTime.of(end, LocalTime.MAX));

        try (InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
             ServletOutputStream out = response.getOutputStream();
             XSSFWorkbook excel = new XSSFWorkbook(in);

        ){
            XSSFSheet sheet = excel.getSheet("sheet1");
            sheet.getRow(1).getCell(1).setCellValue(begin + "至" + end);
            //获得第4行
            XSSFRow row = sheet.getRow(3);
            //获取单元格
            row.getCell(2).setCellValue(businessData.getTurnover());
            row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessData.getNewUsers());
            row = sheet.getRow(4);
            row.getCell(2).setCellValue(businessData.getValidOrderCount());
            row.getCell(4).setCellValue(businessData.getUnitPrice());
            for (int i = 0; i < 30; i++) {
                LocalDate date = begin.plusDays(i);
                //准备明细数据
                businessData = workspaceService.getBusinessData(LocalDateTime.of(date,LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));
                row = sheet.getRow(7 + i);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessData.getTurnover());
                row.getCell(3).setCellValue(businessData.getValidOrderCount());
                row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessData.getUnitPrice());
                row.getCell(6).setCellValue(businessData.getNewUsers());
            }

            excel.write(out);
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
